<!-- 客户端授权 -->
<template>
  <div>
    <!-- <a-modal :title="$t('Client-authorization')" 
						v-model='authorize' @cancel='cancelhandle' width='48%' 
						@ok='handleClient' 
						:cancelText="$t('Cancel')" :okText="$t('Sure')" :maskClosable='false'
						> -->
    <a-drawer
			:title="$t('Client-authorization')" 
			width='40%' 
			:visible="authorize"
			:body-style="drawerBodyStyle"
			@close="cancelHandle"
			:maskClosable='false'
		>
      <a-form :form='forma' :layout="formDirection">
				<!-- 基本信息 -->
				<div class="form-title">{{$t('Base_info')}}</div>
        <a-form-item :label="$t('Create')+'iSCSI '+$t('Client')" v-bind='formlayout'>
					<a-input
						v-decorator="['iqn',{
							rules:[
								{required:true,message:$t('Enter')+$t('Client') + $t('Name')},
								// {pattern:/^[a-zA-Z][0-9a-zA-Z-]{2,31}$/,message: $t('Not_enter_special_characters4')}
								{pattern:/^iqn\.[0-9]{4}\-[0-9]{2}([\.:\-0-9a-zA-Z]+)$/,message: $t('Iqn-reg')}
							]
							}]" 
						:placeholder="$t('Enter')+$t('Client') + $t('Name')" 
					/>
					<!-- :addonBefore="predate" -->
        </a-form-item>
				<a-form-item label="target" v-bind="formlayout">
					<a-spin :spinning="isLoadingForm">
          <a-select 
						v-decorator="['target',{
              rules:[{required:true,message:$t('Choose')+'target'}]
          	}]"  
						:placeholder="$t('Choose')+'target'"
						@change="changeTarget"
					>
            <a-select-option v-for="i in basedata.targets" :value='i' :key="i">{{i}}</a-select-option>
          </a-select>
					</a-spin>
        </a-form-item>
				<div class="form-title">
					<a-checkbox :checked="chapChecked" @change="changeChapCheck">
						<span v-if="$store.state.language=='zh'">启用chap认证</span>
						<span v-else>Enable Chap Authentication</span>
					</a-checkbox>
				</div>
				<!-- chap认证 -->
				<a-row :gutter="15" v-if="chapChecked">
					<!-- 用户名 -->
					<a-col :span="12">
						<a-form-item :label="$t('User')+$t('Name')" v-bind='formlayout'>
							<a-input 
								v-decorator="['username',{
									rules:[
										{required:true,message:$t('Enter')+$t('User') + $t('Name')},
										{pattern:/^[a-zA-Z][0-9a-zA-Z.:@_-]{7,63}$/,message: $t('Not_enter_special_characters2')}]
									}]"
								:placeholder="$t('Enter')+$t('User') + $t('Name')">
							</a-input>
						</a-form-item>
					</a-col>
					<!-- 密码 -->
					<a-col :span="12">
						<a-form-item :label="$t('Password')" v-bind='formlayout'>
							<a-input-password v-decorator="['pwd',{
								rules:[
									{required:true,message:$t('Enter') + $t('Password')},
									{pattern:/^[0-9a-zA-Z@_/-]{12,16}$/,message: $t('Not_enter_special_characters3')}
								]}]"
									:placeholder="$t('Enter') + $t('Password')">
							</a-input-password>
						</a-form-item>
					</a-col>
				</a-row>
				<div class="form-title">
					<a-checkbox :checked="twoWayChecked" @change="changeTwoWayCheck">
						<span v-if="$store.state.language=='zh'">启用双向认证</span>
						<span v-else>Enable Two-Way Authentication</span>
					</a-checkbox>
				</div>
				<!-- 双向认证 -->
				<a-row :gutter="15" v-if="twoWayChecked">
					<!-- 反向用户名 -->
					<a-col :span="12">
						<a-form-item :label="$t('Reverse-user-name')" v-bind='formlayout'>
							<a-input 
								v-decorator="['reverse_username',{
									rules:[
										{required:true,message:$t('Enter')+$t('Reverse-user-name')},
										{pattern:/^[a-zA-Z][0-9a-zA-Z.:@_-]{7,63}$/,message: $t('Not_enter_special_characters2')}]
									}]"
								:placeholder="$t('Enter')+$t('Reverse-user-name')">
							</a-input>
						</a-form-item>
					</a-col>
					<!-- 反向用户密码 -->
					<a-col :span="12">
						<a-form-item :label="$t('Reverse-user-password')" v-bind='formlayout'>
							<a-input-password v-decorator="['reverse_pwd',{
								rules:[
									{required:true,message:$t('Enter') + $t('Reverse-user-password')},
									{pattern:/^[0-9a-zA-Z@_/-]{12,16}$/,message: $t('Not_enter_special_characters3')}
								]}]"
									:placeholder="$t('Enter') + $t('Reverse-user-password')">
							</a-input-password>
						</a-form-item>
					</a-col>
				</a-row>
        <!-- 其他 -->
				<div class="form-title">{{$t('Other')}}</div>
				<!-- 所属主机组 -->
        <a-form-item :label="$t('Host-group')" v-bind="formlayout">
					<a-spin :spinning="isLoadingHostGroup">
          <a-select 
						v-decorator="['host_group',{
              // rules:[{required:true,message:$t('Choose')+$t('Host-group')}]
          	}]"
						:placeholder="$t('Choose')+$t('Host-group')"
            @change="changeHostGroup"
            allowClear
					>
						<a-select-option v-for="(host,index) in hostGroup" :value='host' :key="index">{{host}}</a-select-option>
          </a-select>
					</a-spin>
        </a-form-item>
				<!--配置LUN-->
				<a-form-item
          v-if="!hostGroupValue"
          :label="$t('Config-lun')"
          v-bind="formlayout"
        >
					<a-spin :spinning="isLoadingForm">
					<a-transfer
						:data-source="lunData"
						:titles="[$t('Assign-lun'), $t('Selected-lun')]"
						show-search
						:filter-option="filterOption"
						:target-keys="targetKeys"
						:render="renderRowData"
						@change="handleChangeTransfer"
						:listStyle="{width:'45%',height:'350px'}"
						:locale="transferLocale"
					/>
					</a-spin>
					<!-- @search="handleSearch" -->
          <!-- <a-input-password v-decorator="['pwd',{
						rules:[{required:true,message:$t('Enter') + $t('Password')},
							{pattern:/^[0-9a-zA-Z@_/-]{12,16}$/,message: $t('Not_enter_special_characters3')}
						]}]"
							:placeholder="$t('Enter') + $t('Password')"></a-input-password> -->
        </a-form-item>
      </a-form>
			<div class="draw-bottom-btn">
				<a-button :style="{ marginRight: '8px' }" @click="cancelHandle" style="width:80px">
					{{$t('Cancel')}}
				</a-button>
				<a-button type="primary" @click="handleClient" :loading="isAddLoading" style="width:80px">
					{{$t('Sure')}}
				</a-button>
			</div>
		</a-drawer>
    <!-- </a-modal> -->
  </div>
</template>

<script>
import request from '@/request/request'

export default {
  props: {
    visible: {
      type: Boolean,
      required: true,
    },
    lunData: {
      type: Array,
      required: true,
    },
    basedata: {
      type: Object,
      required: true
    },
		isLoadingForm: {
			type: Boolean,
      required: true,
		}
  },
  data() {
    return {
      authorize: false,
      forma: this.$form.createForm(this),
      formDirection: 'vertical',
	    formlayout: {
	      // labelCol:{span:6},
	      // wrapperCol:{span:18}
	    },
      predate: '',
      isAddLoading: false,
      targetKeys: [],
      transferLocale: {
				itemUnit: '',
				itemsUnit: '',
				notFoundContent: this.$t('List-empty'),
				searchPlaceholder: this.$t('Enter-lun-or-pool')
			},
      chapChecked: false,
			twoWayChecked: false,
      drawerBodyStyle: {
        paddingBottom: '50px !important',
      },
      hostGroupValue: '',
			isLoadingHostGroup: false,
			hostGroup: []
    }
  },

  watch: {
    visible(newValue) {
      if(newValue) {
        this.pre();
      }
      this.authorize = newValue;
    }
  },

  methods: {
    //客户端授权
    handleClient(e){
	    e.preventDefault();
	    this.forma.validateFields((err,val)=>{
	      if(!err){
					this.isAddLoading = true;
					// this.spinning = true
					request('put', 'block/iscsi/', {
						target: val.target,
						iqn: this.predate+val.iqn,
						username: this.chapChecked ? val.username : undefined,
						password: this.chapChecked ? val.pwd : undefined,
						luns: this.targetKeys,
						mutual_username: this.twoWayChecked ? val.reverse_username : undefined,
						mutual_password: this.twoWayChecked ? val.reverse_pwd: undefined,
						host_group: val.host_group,
					}).then(res=>{
						// this.model(res.data.id) //返回模板
            // this.notice(res.data.id, res.data.params, res.data.flag) //通知列表显示
						// this.gettask()  //任务栏信息
						// this.spinning = false
						if(res.data.flag == 0) {
              //更新数据
              this.$emit('updateData',val);
						}else {
							this.model(res.data.id) //返回模板
            	this.notice(res.data.id, res.data.params, res.data.flag) //通知列表显示
						}
						// this.forma.resetFields();
					}).finally(() => {
            this.$emit('closeClientAuthDrawer');
						this.isAddLoading = false;
					})
	      }
	    })
		},

    // 处理iqn前缀
    pre() {
			let date = new Date();
			let month = (date.getMonth()+1) < 10 ? '0'+(date.getMonth()+1) : (date.getMonth()+1);
			this.predate = 'iqn.' + date.getFullYear() + '-' + month + '.com.wz:';
		},

    //改变穿梭框选项
		handleChangeTransfer(targetKeys, direction, moveKeys) {
			// console.log(targetKeys, direction, moveKeys);
			this.targetKeys = targetKeys;
    },

		//穿梭框搜索
		filterOption(inputValue, option) {
			return option.title.indexOf(inputValue) > -1;
		},

		//渲染穿梭框的数据格式
		renderRowData(item) {
			return item.title;
		},

    //改变chap认证的选择状态
		changeChapCheck(e) {
			this.chapChecked = e.target.checked;
		},

		//改变双向认证的选择状态
		changeTwoWayCheck(e) {
			this.twoWayChecked = e.target.checked;
		},

		// 改变target选择
		changeTarget(value) {
			this.getUserGroupByTarget(value)
		},

		// 通过target获取用户组
		async getUserGroupByTarget(target) {
			this.isLoadingHostGroup = true;
			this.forma.setFieldsValue({
				host_group: undefined
			})
      this.hostGroupValue = '';
			this.hostGroup = [];
			const res = await this.$api.iscsi.getUserGroupByTargetRequest({target});
			console.log('对应的主机组', res)
			if(res && res.data) {
				this.hostGroup = res.data.group;
			}
			this.isLoadingHostGroup = false;
		},

    //关闭客户端授权
    cancelHandle(){
      this.$emit('closeClientAuthDrawer');
			this.chapChecked = false;
			this.twoWayChecked = false;
	    this.forma.resetFields();
	  },

    //改变所属主机组
    changeHostGroup(value) {
      this.hostGroupValue = value;
    },
  },
}
</script>
<style scoped>
  .draw-bottom-btn {
		/* float: right;
		padding-bottom: 20px; */
    position: absolute;
    bottom: 0;
    width: 100%;
    border-top: 1px solid #e8e8e8;
    padding: 10px 16px;
    text-align: right;
    left: 0;
    background: #fff;
    border-radius: 0 0 4px 4px;
	}
  .form-title {
		font-size: 14px;
		color: #333;
		margin-bottom: 10px;
    font-weight: 700;
	}
	.ant-form-vertical .ant-form-item {
		padding-bottom: 0;
	}
</style>